import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api", // 从环境变量获取baseURL
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么

    // 添加token到请求头
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 添加时间戳防止缓存
    if (config.method === "get") {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }

    // 显示loading
    if (config.showLoading !== false) {
      // 这里可以调用全局loading组件
      console.log("显示loading");
    }

    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 隐藏loading
    if (response.config.showLoading !== false) {
      console.log("隐藏loading");
    }

    const { data, status } = response;

    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (status === 200) {
      // 这里可以根据后端的响应结构进行调整
      if (data.code === 200 || data.code === 0) {
        return data;
      } else {
        // 业务错误处理
        ElMessage.error(data.message || "请求失败");
        return Promise.reject(new Error(data.message || "请求失败"));
      }
    } else {
      ElMessage.error("网络错误");
      return Promise.reject(new Error("网络错误"));
    }
  },
  (error) => {
    // 隐藏loading
    //error.config ? .showLoading !== false
    if (1) {
      console.log("隐藏loading");
    }

    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            localStorage.removeItem("token");
            window.location.href = "/login";
          });
          break;
        case 403:
          ElMessage.error("没有权限访问该资源");
          break;
        case 404:
          ElMessage.error("请求的资源不存在");
          break;
        case 500:
          ElMessage.error("服务器内部错误");
          break;
        default:
          //data ? .message || `请求失败: ${status}`
          ElMessage.error(1);
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error("网络连接失败，请检查网络");
    } else {
      // 请求配置出错
      ElMessage.error("请求配置错误");
    }

    return Promise.reject(error);
  }
);

// 封装GET请求
export const get = (url, params, config = {}) => {
  return service.get(url, { params, ...config });
};

// 封装POST请求
export const post = (url, data, config = {}) => {
  return service.post(url, data, config);
};

// 封装PUT请求
export const put = (url, data, config = {}) => {
  return service.put(url, data, config);
};

// 封装DELETE请求
export const del = (url, config = {}) => {
  return service.delete(url, config);
};

// 封装PATCH请求
export const patch = (url, data, config = {}) => {
  return service.patch(url, data, config);
};

// 封装文件上传
export const upload = (url, file, config = {}) => {
  const formData = new FormData();
  formData.append("file", file);

  return service.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    ...config,
  });
};

// 封装文件下载
export const download = (url, params, filename) => {
  return service
    .get(url, {
      params,
      responseType: "blob",
    })
    .then((response) => {
      const blob = new Blob([response.data]);
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = filename || "download";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
    });
};

// 导出axios实例
export default service;
